package com.zzw.mvvm.base;

import android.os.Bundle;
import android.util.Log;

import com.zzw.mvvm.utils.Utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * auth zzw
 * 2019 03 22
 *
 * @param <T>
 */
public abstract class BaseActivity<T extends BaseViewModel> extends AppCompatActivity {
    public String TAG = this.getClass().getSimpleName();
    public Unbinder unBinder;
    public T viewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        Utils.getActivityList().add(this);
        unBinder = ButterKnife.bind(this);
        createViewModel();
        bindViewModel();

    }

    /**
     * 获取ViewModelProvider
     *
     * @return ViewModelProvider
     */
    public ViewModelProvider getModelProvider() {
        ViewModelProvider.Factory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication());
        ViewModelProvider viewModelProvider = new ViewModelProvider(this, factory);
        return viewModelProvider;
        // viewModel = viewModelProvider.get(T);
    }

    /**
     * 通过泛型自动直接获取ViewModel
     *
     * @return T
     */
    public T createViewModel() {
        if (getType() == null) {
            Log.e(TAG, "无法获取当前类型，未指定或者创建失败，选择其他方式创建");
            return null;
        }
        viewModel = getModelProvider().get(getType());
        return viewModel;
    }

    /**
     * 通过传入泛型直接获取ViewModel--适用于可能存在多个viewModel
     *
     * @return T
     */
    public T createViewModel(Class<T> c) {
        viewModel = getModelProvider().get(c);
        return viewModel;
    }

    /**
     * 获取当前泛型类型m
     */
    public Class<T> getType() {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            Log.i(TAG, "ParameterizedType=" + parameterizedType.getActualTypeArguments()[0]);
            return (Class<T>) parameterizedType.getActualTypeArguments()[0];
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unBinder != null) {
            unBinder.unbind();
        }
        Utils.getActivityList().remove(this);
    }

    public abstract int getLayoutId();

    /**
     * 绑定监听事件
     */
    public abstract void bindViewModel();

}
